package pri.syl.xiaowu.websocket.core.template;

import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.util.CharsetUtil;
import lombok.Data;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

/**
 * @Author YunLong
 * @Date 2021/7/18 18:10
 * @Description websocket消息模板用来转换消息
 **/
@Data
public class WebsocketMessageTemplate {
    private WebSocketFrame webSocketFrame;

    public WebsocketMessageTemplate(WebSocketFrame webSocketFrame) {
        this.webSocketFrame = webSocketFrame;
    }

    public String convertText() {
        return webSocketFrame.content().toString(CharsetUtil.UTF_8);
    }


    public byte[] convertBytes() {
        return webSocketFrame.content().array();
    }

    /**
     * 通过免去中间交换的内存拷贝, 提升IO处理速度; 直接缓冲区的内容可以驻留的正常垃圾回收以外 堆。
     * DirectBuffer 在 -XX:MaxDirectMemorySize=xxM大小限制下, 使用 Heap 之外的内存
     *
     * @return byte[]
     * @apiNote [附加描述]
     * @author YunLong
     * @date 2021/7/19 9:34
     */
    public byte[] convertBytesDirectBuffer() {
        ByteBuf content = webSocketFrame.content();
        byte[] array = new byte[content.readableBytes()];
        content.duplicate().readBytes(array);
        return array;
    }

    public void transferTo(String filePath) throws IOException {
        try (FileOutputStream fileOutputStream = new FileOutputStream(filePath);
             FileChannel fileChannel = fileOutputStream.getChannel()) {
            fileChannel.write(webSocketFrame.content().nioBuffer());
        }
    }
}
